import Vue from 'vue'
import Router from 'vue-router'
import routes from './routers'
import store from '@/store'
import iView from 'view-design'
import { getLocked, setToken, getToken, setTitle } from '../libs/util'
import config from '@/config'
import { getMenuList } from '../api/sys/menu'
import Main from '@/components/main'
import medium from '@/components/medium/medium.vue'

const { homeName } = config

const LOGIN_PAGE_NAME = 'login'

const error_404 = {
  path: '*',
  name: 'error_404',
  meta: {
    hideInMenu: true
  },
  component: () => import('@/view/error-page/404.vue')
}

const getTreeMenu = (arr, parentId) => {
  let temp = []

  let treeArr = arr
  treeArr.forEach((item, index) => {
    if (item.parentId === parentId) {
      let obj = {}
      obj.path = treeArr[index].path
      obj.name = treeArr[index].name
      obj.meta = {}
      obj.meta.icon = treeArr[index].icon
      obj.meta.title = treeArr[index].title
      if (treeArr[index].showAlways) {
        obj.meta.showAlways = treeArr[index].showAlways
      }
      if (treeArr[index].hideInBread) {
        obj.meta.hideInBread = treeArr[index].hideInBread
      }
      if (treeArr[index].hideInMenu) {
        obj.meta.hideInMenu = treeArr[index].hideInMenu
      }
      if (getTreeMenu(treeArr, treeArr[index].id).length > 0) {
        // 递归调用此函数
        obj.children = getTreeMenu(treeArr, treeArr[index].id)
      }
      if (treeArr[index].view === 'Main') {
        obj.component = Main
      } else if (treeArr[index].view === 'Medium') {
        obj.component = medium
      } else if (treeArr[index].view === null) {
      } else {
        const a = treeArr[index].view.replace('/view/', '')
        // obj.component = () => import(`@/view/${a}`)
        obj.component = resolve => require([`@/view/${a}`], resolve)
      }
      temp.push(obj)
    }
  })

  return temp
}

const addMenu = (to, from, next, n) => {
  getMenuList().then(res => {
    let main = getTreeMenu(res.data, 0)
    main.push(error_404)
    store.commit('setMenu', main)
    router.options.routes = store.state.app.menu.concat(routes)
    router.addRoutes(store.state.app.menu)
    if (n) {
      next({ ...to, replace: true })
    } else {
      next()
    }
  })
}

Vue.use(Router)

const router = new Router({
  routes: routes,
  mode: 'history'
})

router.beforeEach((to, from, next) => {
  iView.LoadingBar.start()
  const token = getToken()
  if (!token && to.name !== LOGIN_PAGE_NAME) {
    // 未登录且要跳转的页面不是登录页
    store.commit('setTagNavList', [])
    store.commit('setMenu', [])
    next({
      name: LOGIN_PAGE_NAME // 跳转到登录页
    })
  } else if (!token && to.name === LOGIN_PAGE_NAME) {
    // 未登陆且要跳转的页面是登录页
    store.commit('setTagNavList', [])
    store.commit('setMenu', [])
    next() // 跳转
  } else if (token && to.name === LOGIN_PAGE_NAME) {
    // 已登录且要跳转的页面是登录页
    next({
      name: homeName // 跳转到homeName页
    })
  } else {
    if (store.state.user.hasGetInfo) {
      if (store.state.app.menu.length === 0) {
        addMenu(to, from, next)
      } else {
        if (getLocked() && to.name !== 'locked') {
          next({
            name: 'locked' // 跳转到homeName页
          })
        } else if (getLocked() && to.name === 'locked') {
          next()
        } else if (!getLocked() && to.name === 'locked') {
          next({
            name: homeName // 跳转到homeName页
          })
        } else {
          next()
        }
      }
    } else {
      store.dispatch('getUserInfo').then(user => {
        // 拉取用户信息，通过用户权限和跳转的页面的name来判断是否有权限访问;access必须是一个数组，如：['super_admin'] ['super_admin', 'admin']
        addMenu(to, from, next, true)
      }).catch(() => {
        setToken('')
        store.commit('setTagNavList', [])
        store.commit('setMenu', [])
        next({
          name: 'login'
        })
      })
    }
  }
})

router.afterEach(to => {
  setTitle(to, router.app)
  iView.LoadingBar.finish()
  window.scrollTo(0, 0)
})

export default router
